<script setup lang="ts">
  import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
  import { useHttp } from './request/request'
  import { useWxSdk } from './utiles/wx-sdk'
  import weixin from 'weixin-js-sdk'

  const { exeWxConfig } = useWxSdk()
  const { get, post } = useHttp()

  onLaunch((query) => {})
  onShow((query) => {
    let q: {
      ewm: '1'
      count: '96'
      num: '239'
      bid: '33547'
      unionid: 'oSqUJ0uLmgiz7Q-pMwQkIMaRpdls'
      openid: 'oPbPOw6Sk6oGl5KaX9UKEpuCpKrw'
      bname: '孜然界烧烤张湾店'
      sn: '222110785161563278'
      mac: ''
    }

    // 判断是否有参数，有参数更新本地参数
    if (window.location.href.includes('?')) {
      const url_c = decodeURIComponent(window.location.href)

      // url_c.substring(0, url_c.length - 2)
      console.log('url_c', url_c.replace(/#\//g, ''))

      q = queryURLParams(url_c.replace(/#\//g, '')) as any
      uni.setStorageSync('query', JSON.stringify(q))

      // console.log(decodeURIComponent(window.location.href).split('?')[1])

      uni.setStorageSync('query_url', JSON.stringify(url_c.split('?')[1]))
    } else {
      uni.getStorageSync('query') && (q = JSON.parse(uni.getStorageSync('query')))
    }

    uni.request({
      url: 'http://mawifi.yfwnm.com/api/jssdk.php',
      header: {
        'content-Type': 'application/json',
      },
      data: {
        url: window.location.href.split('#')[0],
      },
      method: 'POST',
      success: function (res: any) {
        const { data } = res

        // 获取微信认证
        exeWxConfig({
          ...data,
          success: () => {
            getLocate(q.bid)
          },
          error: (err: any) => {
            uni.showModal({
              title: '提示',
              content: '授权失败',
              showCancel: true,
              success: ({ confirm, cancel }) => {},
            })
          },
        })
      },
    })
  })
  onHide(() => {
    // TODO  离开页面清理数据

    console.log('onHide')
  })

  // 获取当前位置
  const getLocate = (bid: string) => {
    wx.getLocation({
      type: 'gcj02',
      success: function (res: any) {
        console.log('getLocate', res)
        getDistance(res.latitude, res.longitude, bid)

        uni.setStorageSync('location', `${res.longitude + ',' + res.latitude}`)

        if (res.errMsg === 'getLocation:ok') {
        }
        if (res.errMsg === 'getLocation:cancel') {
        }
      },
      complete: function (res: any) {
        console.log('getLocatecomplete', res)
      },
      fail: function (res: any) {
        console.log('getLocatefail', res)
      },
    })

    // if (!is_wx()) {
    //   MapLoader({
    //     succes: async (res) => {
    //       const { lat, lng } = res.position

    //       getDistance(lat, lng, bid)
    //     },
    //     error: (err) => {
    //       console.log(err)
    //     },
    //   })
    // } else {
    //   wx.getLocation({
    //     type: 'gcj02',
    //     success: function (res: any) {
    //       console.log('getLocate', res)
    //       getDistance(res.latitude, res.longitude, bid)

    //       if (res.errMsg === 'getLocation:ok') {
    //       }
    //       if (res.errMsg === 'getLocation:cancel') {
    //       }
    //     },
    //     cancel: function (res: { errMsg: string }) {
    //       if (res.errMsg === 'getLocation:cancel') {
    //       }
    //     },
    //     complete: function (res: any) {
    //       console.log('getLocatecomplete', res)
    //     },
    //     fail: function (res: any) {
    //       console.log('getLocatefail', res)
    //     },
    //   })
    // }
  }

  // 获取距离
  const getDistance = async (latitude: string, longitude: string, bid: string) => {
    const { data, code } = await post('index/get_distance', {
      bid,
      latitude,
      longitude,
    })
    console.log('position', data)
    if (code == 0) {
      uni.showModal({
        title: '提示',
        content: '您的位置超出服务范围将无法使用连WiF,领红包功能,酒店服务功能',
        success: function (res) {
          // disabled.value = 'disabled'
        },
      })
    } else if (code == 1) {
      // disabled.value = ''
    }
  }

  function queryURLParams(URL: string) {
    // const url = location.search; // 项目中可直接通过search方法获取url中"?"符后的字串
    let url = URL.split('?')[1]
    let obj: { [key: string]: any } = {} // 声明参数对象
    let arr = url.split('&') // 以&符号分割为数组
    for (let i = 0; i < arr.length; i++) {
      let arrNew = arr[i].split('=') // 以"="分割为数组
      obj[arrNew[0]] = arrNew[1]
    }
    return obj
  }
</script>
<style>
  page {
    width: 100%;
    height: 100%;
    line-height: 1.5;
    background: linear-gradient(222deg, #deebff 0%, #ffffff 66%, #ffffff 100%);
    background-repeat: no-repeat;
  }
  a {
    text-decoration: none;
  }

  ::-webkit-scrollbar {
    width: 0; /* Safari,Chrome 隐藏滚动条 */
    height: 0; /* Safari,Chrome 隐藏滚动条 */
    display: none; /* 移动端、pad 上Safari，Chrome，隐藏滚动条 */
  }
</style>
